<template>
  <div>
    <div style="display: flex;align-items:center; margin-bottom: 10px" v-for="(item, index) in timeRanges" :key="index">
      <el-input style="flex: 1;margin-right:10px;" v-model="item.name" placeholder="请输入名称"></el-input>
      <el-time-picker style="flex: 2;" is-range v-model="item.range" value-format="HH:mm:ss" format="HH:mm" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" @change="change"></el-time-picker>
      <el-button style="margin-left: 10px" type="danger" @click="del(index)">删除</el-button>
    </div>
    <el-button v-if="!timeRanges || timeRanges.length < 3" icon="el-icon-plus" @click="add">添加</el-button>
  </div>
</template>

<script>
export default {
  name: "SelectTimeRanges",
  props: {
    /* JSON字符串 */
    value: {
      type: String,
      default: null,
    },
  },
  data() {
    return {
      timeRanges: [],
    };
  },
  watch: {
    value: {
      handler(val) {
        this.timeRanges = [];
        if (val) {
          try {
            const list = JSON.parse(val);
            list.forEach((item) => {
              this.timeRanges.push({
                name: item.name,
                range: [item.startTime, item.endTime],
              });
            });
          } catch (e) {
            console.log("JSON解析出错", val);
          }
        }
      },
      immediate: true,
    },
  },
  methods: {
    add() {
      this.timeRanges.push({ range: null });
    },
    del(i) {
      this.timeRanges.splice(i, 1);
      this.change();
    },
    change() {
      let list = [];
      this.timeRanges.forEach((item) => {
        if (item && item.range && item.range.length >= 2) {
          list.push({
            name: item.name,
            startTime: this.formatTime(item.range[0]),
            endTime: this.formatTime(item.range[1]),
          });
        }
      });
      this.$emit("input", JSON.stringify(list));
    },
    formatTime(time) {
      const [hours, minutes, seconds] = time.split(":").map(Number);
      const h = hours < 10 ? `0${hours}` : hours;
      const m = minutes < 10 ? `0${minutes}` : minutes;
      return `${h}:${m}:00`;
    },
  },
};
</script>

<style scoped lang="scss"></style>
